package www.cskaoyan.com.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;

/**
 * @description:
 * @author: 景天
 * @date: 2023/3/9 15:17
 **/
/*
每发送请求,建立连接,放入线程中,交给线程池进行处理
 */
public class ConnectTask implements Runnable {
    private static final Server SERVER = new Server();

    private Socket socket;

    public ConnectTask(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName()+
                    "-----port:"+socket.getPort()+"-----------working-------");

            InputStream inputStream = socket.getInputStream();
            // 处理请求
            Request request = SERVER.dealRequest(inputStream);

            Response response = null;
            if (request.getMethods().toUpperCase().equals("OPTIONS")){
                // OPTIONS请求不做处理
            }else {
                // 调用分发器分发请求, 获得结果
                Dispatcher dispatcher = new Dispatcher();
                response = dispatcher.dispatch(request);
            }

            // 处理响应
            OutputStream outputStream = socket.getOutputStream();
            SERVER.response(outputStream, response);
            socket.close();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
